<?php
	include('startup.php');
	include("modules/tblfile/fileclass.php");
	if($_FILES['image2']['name'] != "")
	{
		$img = new HelperImage();
		$file = saveFile($conn,$_FILES['image2'],"upload/");
		$arr = array(
			'error' => 'none',
			'imageid' => $file->FileID,
			'imagename' => $file->FileName,
			'imagepath' => $file->FilePath,
			'imagethumbnail' => $img->resizePNG($file->FilePath,100,100)
		);
		
		echo json_encode(array('files' => $arr));
		
	}


function saveFile($conn,$file,$filepath="",$filetypeid="image",$tagkeyword="")
{
	
	$arfile = split('\.', $file['name'] );
	$datafile = array();
	//Filename
	$filename = $arfile[0];
	$extension = strtolower($arfile[1]);
	//convert byte sang KB
	$filesize=($file['size'])/1024;

	
	//get width + height cua file image
	$width=0;//default = 0
	$height=0;
	if($filetypeid=="image")
	{
		$size = getimagesize($file['tmp_name']);
		$width=$size[0];
		$height=$size[1];
	}
	
	
	
	//Upload & Save file
	$count=1;
	if (trim($file['tmp_name']) != '') 
	{
		$uploadDir= $filepath;
		
		//Tao thu muc
		$listdir=split("/",	$uploadDir);
		$path=DIR_FILE;
		foreach($listdir as $dir)
		{
			
			if($dir!="")
			{
				$path.=$dir."/";
				if (! is_dir($path))
					mkdir( $path , 0777 );
			}
		}
		
		$uploadDir= DIR_FILE.$filepath;
		
		$datafile['filename']=$filename.".".$extension;
		$datafile['filepath']=$filepath;
		$datafile['filetypeid']=$filetypeid;
		while(file_exists($uploadDir.$datafile['filename']))
		{
			$datafile['filename']=$filename.$count.".".$extension;
			$count++;
		}
		$objfile = new File();
		$objfile->FileName = $datafile['filename'];
		$objfile->FilePath = $datafile['filepath'].$datafile['filename'];
		$objfile->FileType = $filetypeid;
		$objfile->Status = "temp";
		$objfile->insert($conn);
		move_uploaded_file($file['tmp_name'],$uploadDir.$datafile['filename']);
	}
	
	return $objfile;
	
}
?>